<?php

namespace app\admin\controller\api;

use addons\ucenter\library\client\Client;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\model;
use app\common\model\Classes;
use app\common\model\CourseDetail;
use fast\Tree;
use think\Db;

/**
 * 管理员
 * @internal
 */
class Admin extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    public function profile()
    {
        $id = $this->request->request('id', 0);
        $admin = \app\admin\model\Admin::where('id', $id)->field('id,username,nickname,avatar,status,logintime,loginfailure,createtime,updatetime,school_id')->find();
        $this->success('', $admin);
    }

    public function group()
    {
        $id = $this->request->request('id');
        $result = AuthGroup::get($id);

        $this->success('', $result);
    }

    public function groups()
    {
        $childrenGroupIds = $this->getChildrenGroupIds(true);
        $groupList = collection(AuthGroup::where('id', 'in', $childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $result = [];

        if ($this->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
        } else {
            $groups = $this->getGroups();

            foreach ($groups as $m => $n) {
                $result = array_merge($result, Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['pid'])));
            }
        }

        $groupName = [];
        foreach ($result as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }
        $groupdata = $groupName;
        $group_ids = $this->getGroupIds();

        $this->success('', compact('childrenGroupIds', 'groupdata', 'group_ids'));

    }

    public function authGroup()
    {
        $ids = $this->request->request('ids/a');
        $list = AuthGroup::all($ids);

        $this->success('', $list);
    }

    public function userGroups()
    {
        $id = $this->request->request('id');

        $user_groups = AuthGroupAccess::alias('aga')
            ->join('__' . strtoupper('auth_group') . '__ ag', 'aga.group_id = ag.id', 'LEFT')
            ->field('aga.uid,aga.group_id,ag.id,ag.pid,ag.name,ag.rules')
            ->where("aga.uid='{$id}' and ag.status='normal'")
            ->select();
        $this->success('', $user_groups);
    }

    public function userGroupAccess()
    {
        $uid = $this->request->request('uid');
        $result = AuthGroupAccess::where(['uid' => $uid])->select();
        $this->success('', $result);
    }


}